package com.xinguan.filter;
import cn.hutool.core.collection.ConcurrentHashSet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 陈俊行
 * @Date: 2023/11/12/16:51
 * @Description:
 */
@Component
@Slf4j
public class MyFilter implements Filter {

    /**
     * urlSet
     * @Description
     * 用于存放 放行的路径
     */
    private ConcurrentHashSet<String> urlSet = new ConcurrentHashSet<>();

    public void exclusionUrl(String url) {
        this.urlSet.add(url);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("登陆注册拦截器被初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //放行接口
        String url = request.getRequestURL().toString();
        if (urlSet.contains(url)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //校验
        String token = request.getHeader("Authorization");
        if (token != null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            response.sendRedirect("/");
        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        log.info("拦截器销毁");
    }
}